package cn.wolfcode.web.hander;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.util.Request;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

@Component
public class IsAdmin implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //判断是否是动态资源
        if (handler instanceof HandlerMethod) {

            //判断是否登录
            Employee user_success = (Employee) request.getSession().getAttribute("USER_SUCCESS");
            if (user_success != null) {

                //判断是否是超级管理员
                if (user_success.isAdmin()) {
                    System.out.println("=====================================");
                    return true;
                }

                //自定义权限注解
                Request methodAnnotation = ((HandlerMethod) handler).getMethodAnnotation(Request.class);
                if (methodAnnotation == null) {
                     return true;
                }

                //遍历用户的权限集合
                List<Permission> user_message = (List) request.getSession().getAttribute("USER_MESSAGE");
                for (Permission o : user_message) {
                    System.out.println(o);
                    if (methodAnnotation.expression().equals(o.getExpression())) {
                        return true;
                    }

                }
                //判断是页面还是json
                ResponseBody methodAnnotation1 = ((HandlerMethod) handler).getMethodAnnotation(ResponseBody.class);
                if (methodAnnotation1 != null) {
                    response.setContentType("application/json;charset=utf-8");
                    System.out.println("===================================================");
                    JsonResult jsonResult = new JsonResult();
                    jsonResult.setSuccess(false);
                    jsonResult.setMsg("没有权限");
                    response.getWriter().write(JSON.toJSONString(jsonResult));

                } else {
                    response.sendRedirect("/employee/nopermission");
                }
                return false;
            }
        }

        return true;
    }
}
